package com.kuhh.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;

import com.kuhh.pojo.User;

@WebFilter(value = "/admin/*", initParams = {
        @WebInitParam(name = "encoding", value = "UTF-8")
})
public class AuthenticationFilter implements Filter {

    private String encoding;

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        //设置编码
        response.setCharacterEncoding(encoding);
        HttpServletRequest req = (HttpServletRequest) request;
        req.setCharacterEncoding(encoding);
        User user = (User) req.getSession().getAttribute("loginUser");
        Byte type = user.getUserType();
        if (type != 1) {
            //不是管理员，跳转到错误页面
            req.setAttribute("msg", "抱歉，您没有权限访问！");
            req.getRequestDispatcher("/WEB-INF/pages/error.jsp").forward(req, response);
        } else {
            chain.doFilter(req, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //过滤器初始化的时候调用该方法
        encoding = filterConfig.getInitParameter("encoding");
        //默认值是UTF-8
        if (encoding == null) {
            encoding = "UTF-8";
        }
    }

}
